package jltx.fragmentpageframework.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.StaticLayout;
import android.util.AttributeSet;
import android.widget.TextView;

import jltx.fragmentpageframework.R;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2017/06/24.
 */

@SuppressLint("AppCompatCustomView")
public class ChangeColorImageTextView extends TextView{

    private Paint mSelectImgPaint;
    private Paint mTextPaint;
    private Paint mUnSelectImgPaint;

    private Bitmap mSelectImgBitmap;
    private Bitmap mUnSelectImgBitmap;


    private int iconWidth;
    private int iconPadding;
    private int iconHeight;

    private float mAlpha;  //0..........1

    private int selectMskTextColor;
    private int unSelectMskTextColor;
    private float mFontHeight;
    private float mTextWidth;

    public ChangeColorImageTextView(Context context) {
        super(context);
        initArray(context,null);
    }

    public ChangeColorImageTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initArray(context,attrs);
    }

    public ChangeColorImageTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initArray(context,attrs);
    }

    private void initArray(Context context,AttributeSet attrs){
        selectMskTextColor = ContextCompat.getColor(context, R.color.colorGreenWeChat);
        unSelectMskTextColor = ContextCompat.getColor(context, R.color.colorGrayWeChat);
        mSelectImgPaint = new Paint();
        mTextPaint = new Paint();
        mUnSelectImgPaint = new Paint();

        mSelectImgPaint.setAntiAlias(true);
        mTextPaint.setAntiAlias(true);
        mUnSelectImgPaint.setAntiAlias(true);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ChangeColorView);
        int n = a.getIndexCount();

        Drawable unSelectMskDrawable = null;
        Drawable selectMskDrawable = null;
        for (int i=0; i < n; i++){
            int attr = a.getIndex(i);
            switch (attr){
                case R.styleable.ChangeColorView_selectMask:
                    selectMskDrawable = a.getDrawable(attr);
                    break;
                case R.styleable.ChangeColorView_unSelectMask:
                    unSelectMskDrawable = a.getDrawable(attr);
                    break;
                case R.styleable.ChangeColorView_selectMaskColor:
                    selectMskTextColor = a.getColor(attr,selectMskTextColor);
                    break;
                case R.styleable.ChangeColorView_unSelectMaskColor:
                    unSelectMskTextColor = a.getColor(attr,unSelectMskTextColor);
                    break;
            }
        }
        a.recycle();


        if(unSelectMskDrawable != null){
            setCompoundDrawablesWithIntrinsicBounds(null, unSelectMskDrawable, null, null);
        }

        if (unSelectMskDrawable == null || selectMskDrawable == null) {
            throw new RuntimeException("'focus_icon' and 'defocus_icon' attributes should be defined");
        }

        iconWidth = unSelectMskDrawable.getIntrinsicWidth();
        iconHeight = unSelectMskDrawable.getIntrinsicHeight();

        unSelectMskDrawable.setBounds(0, 0, iconWidth, iconHeight);
        selectMskDrawable.setBounds(0, 0, iconWidth, iconHeight);

        iconPadding = getCompoundDrawablePadding();
        Paint.FontMetrics fontMetrics = getPaint().getFontMetrics();
        mFontHeight = (float) Math.ceil(fontMetrics.descent - fontMetrics.ascent);
        mTextWidth = StaticLayout.getDesiredWidth(getText(), getPaint());

        mUnSelectImgBitmap = getBitmapFromDrawable(unSelectMskDrawable);
        mSelectImgBitmap = getBitmapFromDrawable(selectMskDrawable);

    }

    public void setIconBottomTextColor(@ColorRes int unselectColor, @ColorRes int selectColor){
        unSelectMskTextColor = getResources().getColor(unselectColor);
        selectMskTextColor = getResources().getColor(selectColor);
        invalidate();
    }

    public  void setIconBottomText(CharSequence text) {
        setText(text);
        Paint.FontMetrics fontMetrics = getPaint().getFontMetrics();
        mFontHeight = (float) Math.ceil(fontMetrics.descent - fontMetrics.ascent);
        mTextWidth = StaticLayout.getDesiredWidth(getText(), getPaint());
        invalidate();
    }
    public void setIconMaskDrawable(@DrawableRes int resUnselect, @DrawableRes int resSelect){
        Drawable unSelectMskDrawable = this.getResources().getDrawable(resUnselect);
        Drawable selectMskDrawable = this.getResources().getDrawable(resSelect);

        if(unSelectMskDrawable != null && selectMskDrawable != null){
            if(unSelectMskDrawable != null){
                setCompoundDrawablesWithIntrinsicBounds(null, unSelectMskDrawable, null, null);
            }
            iconWidth = unSelectMskDrawable.getIntrinsicWidth();
            iconHeight = unSelectMskDrawable.getIntrinsicHeight();
            unSelectMskDrawable.setBounds(0, 0, iconWidth, iconHeight);
            selectMskDrawable.setBounds(0, 0, iconWidth, iconHeight);
            if(mUnSelectImgBitmap != null && !mUnSelectImgBitmap.isRecycled()){
                mUnSelectImgBitmap.recycle();
                mUnSelectImgBitmap = null;
            }

            if(mSelectImgBitmap != null && !mSelectImgBitmap.isRecycled()){
                mSelectImgBitmap.recycle();
                mSelectImgBitmap = null;
            }
            mUnSelectImgBitmap = getBitmapFromDrawable(unSelectMskDrawable);
            mSelectImgBitmap = getBitmapFromDrawable(selectMskDrawable);
            invalidate();
        }
    }


    private Bitmap getBitmapFromDrawable(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(iconWidth, iconHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        if (drawable instanceof BitmapDrawable) {
            drawable.draw(canvas);
            return bitmap;
        } else {
            throw new RuntimeException("The Drawable must be an instance of BitmapDrawable");
        }
    }


    @Override
    protected void onDraw(Canvas canvas) {
        drawUnSelectIcon(canvas);
        drawSelectIcon(canvas);
        drawUnSelectText(canvas);
        drawSelectText(canvas);
    }

    private void drawUnSelectIcon(Canvas canvas){
        mUnSelectImgPaint.setAlpha((int)(255 * (1 - mAlpha)));
        canvas.drawBitmap(mUnSelectImgBitmap,(getWidth() - iconWidth) / 2,getPaddingTop(),mUnSelectImgPaint);
    }

    private void drawSelectIcon(Canvas canvas){
        mSelectImgPaint.setAlpha((int)(255 *  mAlpha));
        canvas.drawBitmap(mSelectImgBitmap,(getWidth() - iconWidth) / 2,getPaddingTop(),mSelectImgPaint);
    }

    private void drawUnSelectText(Canvas canvas){
        mTextPaint.setColor(unSelectMskTextColor);
        mTextPaint.setAlpha((int)(255 * (1 - mAlpha)));
        mTextPaint.setTextSize(getTextSize());
        canvas.drawText(getText().toString(),(getWidth() - mTextWidth) / 2,getPaddingTop() + iconPadding + iconHeight + mFontHeight/2,mTextPaint);
    }

    private void drawSelectText(Canvas canvas){
        mTextPaint.setColor(selectMskTextColor);
        mTextPaint.setAlpha((int)(255 * mAlpha));
        mTextPaint.setTextSize(getTextSize());
        canvas.drawText(getText().toString(),(getWidth() - mTextWidth) / 2,getPaddingTop() + iconPadding + iconHeight + mFontHeight/2,mTextPaint);
    }


    /**
     * 改变ImageView的蒙层颜色
     * @param offset
     */
    public void changeImageViewDrawable(float offset){
        if(this.mAlpha != offset){
            this.mAlpha = offset;
            invalidate();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        if(mUnSelectImgBitmap != null){
            mUnSelectImgBitmap.recycle();
        }

        if(mSelectImgBitmap != null){
            mSelectImgBitmap.recycle();
        }
        super.onDetachedFromWindow();
    }
}
